package com.crm.sys.tab;

import java.io.IOException;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.tags.RequestContextAwareTag;

import com.google.common.base.Splitter;
import com.crm.sys.model.Configure;
import com.crm.sys.model.ConfigureItem;
import com.crm.sys.service.SysService;
import com.crm.util.Constants;
/**
 *  配置表标签
 * @author Administrator
 *
 */
@Repository
public class JobTag extends RequestContextAwareTag {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3258620188746752599L;
    
	private String calling;  //行业value
    private String value; //传入的默认值
    private int type;  //类型  1 显示内容  2显示下拉框
	public void setValue(String value) {
		this.value = value;
	}
 
	public void setCalling(String calling) {
		this.calling = calling;
	}

	public void setType(int type) {
		this.type = type;
	}

	public JobTag(){  
    }  
      
	@Override
	protected int doStartTagInternal() throws Exception {  
        JspWriter out = this.pageContext.getOut();  
          
        try {  
        	SysService sysService  = (SysService)this.getRequestContext().getWebApplicationContext().getBean("sysService");  
        
        	  try{
        		  //行业对应的配置CODE
        		  String name =  Constants.CALLING_CODE.get(calling);
        		  String outString ="";
        		    switch (type) {
					case 1:
						String names = "";
						Iterable<String> splitStr = Splitter.on(",").trimResults().omitEmptyStrings().split(value);
						for(String s :splitStr){
							ConfigureItem   cf1 = sysService.getConfigureItemByValue(s,name);
							names +=" "+cf1.getName();
						}
					    outString =names;
						break; 
					case 2:
						Configure   cf = sysService.getConfigureByName(name);
						outString = getSelectHtml(cf.getItem(),value);;
						break; 	   
					}
        		 out.print(outString);  
		       	}catch(Exception e1){
		       	 out.print("");  
		       	}
           
        } catch (IOException e) {  
            //e.printStackTrace();  
        }  
          
      
        return EVAL_BODY_INCLUDE;  
    }  
	/**
	 * 
	 * @param list
	 * @param value   默认值
	 * @return
	 * @throws Exception
	 */
	private String getSelectHtml(List<ConfigureItem> list,String value) throws Exception{
		  StringBuffer  s = new StringBuffer();
		  for(ConfigureItem item:list){
			  s.append("<option value='").append(item.getValue()).append("' ").append(item.getValue().equals(value)?"selected >":">").append(item.getName()).append("</option>");
		  }
		 return s.toString();
	}
	
 
    public int doAfterBody() throws JspException{  
       // System.out.println("处理标签体（after body）....");  
        return SKIP_BODY;  
    }  
    public int doEndTag() throws JspException{  
      //  System.out.println("对象正在处理结束标记.....");  
        return EVAL_PAGE;  
    }  
}
